package com.sunxd.zstudy.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 原理；cas + volita state + LockSupport
 *  new CountDownLatch(100)  初始化计数
 *  await() 加入等待队列 并 park（暂停）当前线程
 *  countDown（）-》 state == 0 时， 唤醒所有等待线程
 * @author: 计数
 * 保证线程执行完，可以用join 可以实现同样的功能，等待所有的线程运行结束
 * @date: 2021-03-31 01:00
 **/
public class T10_CountDownLatch {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            list.add(new Thread( () -> {
                for (int j = 0; j < 10000; j++) {
                }
                System.out.println("thread end");
                countDownLatch.countDown();
            }));
        }
        list.forEach(o ->o.start());
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("countDownLatch end ");
    }
}
